package Exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

@Slf4j(topic = "c.TestExerciseSell")
public class ExerciseSell {


    public static void main(String[] args) throws InterruptedException {
        //Vector线程安全
        List<Integer> sellOutList = new Vector<>();
        List<Thread> threadList = new ArrayList<>();
        //多个线程模拟多个窗口售票
        TicketStation  station = new TicketStation(1000);
        for(int i=0;i<2000;i++){
            Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(getRand());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                int sellOutCount = station.sellTicket(getRand());
                sellOutList.add(sellOutCount);
            });
            threadList.add(thread);
            thread.start();
        }

        for (Thread thread : threadList) {
            thread.join();
        }
        log.info(String.valueOf(station.getCount()+sellOutList.stream().mapToInt(i->i).sum()));

    }
    static Random rand = new Random();

    public static int getRand() {
        //返回随机数1到5
        return rand.nextInt(5)+1;
    }
}

class TicketStation{
    //当前剩余票数
    private int count;

    public TicketStation(int count){
        this.count = count;
    }

    //获取当前剩余票数
    public int getCount(){
        return this.count;
    }

    //返回值是本次卖出的票数
    public synchronized int sellTicket(int amount){
        if(this.count >= amount){
            this.count = this.count - amount;
            return amount;
        }else{
            return 0;
        }
    }
}
